<?php
/**
 * @purpose
 * @Author: Madou
 * @Time  : 2022/8/2 20:35
 */

namespace App\Trip\Wechat\Traits;

use EasyWeChat\Kernel\Exceptions\InvalidArgumentException;
use Exception;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;

trait getWechatPayInfoTrait
{
    /**
     * @throws InvalidArgumentException
     * @throws Exception
     */
    function get_pay_info(array $data): array
    {

        $validator = Validator::make($data, [
            "out_trade_no" => "required",
            "description"  => "required",
            "time_expire"  => "required",
            "order_amount" => "required",
            "attach"       => "required",
        ]);

        $notify_url = URL::to("/api/payment/wechat/callback");
        if ($validator->fails()) {
            throw new Exception("参数错误");
        }

        $appUser = $this->userRepo->getMiniAppUserByAppId(auth()->user(), $this->appId);
        $openId  = $appUser?->getOpenId();
        Log::info("get_pay_info:UserId:{$appUser->getUserId()},UserAppId:{$appUser->getAppId()},OpenId:{$openId},AppId:{$this->appId}");
        $app   = $this->wechatPay->getApplication();
        $utils = $app->getUtils();

        if (mb_strlen($data['attach'] ?? '') > 127) {
            throw new Exception("attach error");
        }

        $total     = bcmul(100, $data['order_amount']) * 1;
        $queryData = [
            "mchid"        => $this->wechatPay->getMchId(),
            "out_trade_no" => $data['out_trade_no'],
            "appid"        => $this->appId,
            "time_expire"  => $data['time_expire'] ?? '', // 计算出过期时间 rfc3339
            "description"  => Str::limit($data['description'], 60),
            "notify_url"   => $notify_url,
            "attach"       => (string)($data['attach'] ?? ''),
            "amount"       => [
                "total"    => $total,
                "currency" => "CNY",
            ],
            "payer"        => [
                "openid" => $openId,
            ],
        ];

        $api          = $app->getClient();
        $prepayIdResp = $api->postJson("v3/pay/transactions/jsapi", $queryData)->toArray();
        if (!isset($prepayIdResp['prepay_id'])) {
            Log::error($prepayIdResp);
            throw new Exception($prepayIdResp['message'] ?? "error");
        }
        $prepayId               = $prepayIdResp['prepay_id'];
        $pay_info               = $utils->buildMiniAppConfig($prepayId, $this->appId);
        $pay_info["pay_amount"] = $data['order_amount'];
        return $pay_info;
    }
}